package com.ruoyi.web.controller.substation;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SSubstation;
import com.ruoyi.system.service.ISSubstationService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SArea;
import com.ruoyi.system.service.ISAreaService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 地区Controller
 * 
 * @author ruoyi
 * @date 2023-07-05
 */
@Api(tags = "地区管理")
@RestController
@RequestMapping("/substation/area")
public class SAreaController extends BaseController
{
    @Autowired
    private ISAreaService sAreaService;

    @Autowired
    private ISSubstationService sSubstationService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询地区列表
     */
    @ApiOperation("获取地区列表")
    @PreAuthorize("@ss.hasPermi('substation:area:list')")
    @GetMapping("/list")
    public TableDataInfo list(SArea sArea)
    {
        // 如果是班组长或者组员只能查看绑定的地区
        String leaderId = SecurityUtils.getLeaderId();
        if(StringUtils.isNotBlank(leaderId)) {
            sArea.setUserId(leaderId);
        }
        startPage();
        List<SArea> list = sAreaService.list(sArea.queryWrapper());
        for (SArea area : list) {
            SysUser user = sysUserService.selectUserById(Long.valueOf(area.getUserId()));
            if(StringUtils.isNotNull(user)) {
                area.setUserNickName(user.getNickName());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出地区列表
     */
    @ApiOperation("导出地区列表")
    @PreAuthorize("@ss.hasPermi('substation:area:export')")
    @Log(title = "地区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SArea sArea)
    {
        List<SArea> list = sAreaService.list(sArea.queryWrapper());
        ExcelUtil<SArea> util = new ExcelUtil<SArea>(SArea.class);
        util.exportExcel(response, list, "地区数据");
    }

    /**
     * 获取地区详细信息
     */
    @ApiOperation("获取地区详细")
    @ApiImplicitParam(name = "id", value = "地区ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('substation:area:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        SArea area = sAreaService.getById(id);
        SysUser user = sysUserService.selectUserById(Long.valueOf(area.getUserId()));
        if(StringUtils.isNotNull(user)) {
            area.setUserNickName(user.getNickName());
        }
        return success(area);
    }

    /**
     * 新增地区
     */
    @ApiOperation("新增地区")
    @PreAuthorize("@ss.hasPermi('substation:area:add')")
    @Log(title = "地区", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SArea sArea)
    {
        long count = sAreaService.count(new LambdaQueryWrapper<SArea>()
                .eq(SArea::getAreaName, sArea.getAreaName()));
        if(count > 0){
            throw new ServiceException("区域：" + sArea.getAreaName() + " 已存在");
        }
        return toAjax(sAreaService.save(sArea));
    }

    /**
     * 修改地区
     */
    @ApiOperation("更新地区")
    @PreAuthorize("@ss.hasPermi('substation:area:edit')")
    @Log(title = "地区", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SArea sArea)
    {
        SArea byId = sAreaService.getById(sArea.getId());
        if(!byId.getAreaName().equals(sArea.getAreaName())) {
            long count = sAreaService.count(new LambdaQueryWrapper<SArea>()
                    .eq(SArea::getAreaName, sArea.getAreaName()));
            if(count > 0){
                throw new ServiceException("区域：" + sArea.getAreaName() + " 已存在");
            }
        }
        return toAjax(sAreaService.updateById(sArea));
    }

    /**
     * 删除地区
     */
    @ApiOperation("删除地区")
    @ApiImplicitParam(name = "ids", value = "地区ID集合", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('substation:area:remove')")
    @Log(title = "地区", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        for (String id : ids) {
            long count = sSubstationService.count(new LambdaQueryWrapper<SSubstation>()
                    .eq(SSubstation::getAreaId, id));
            if(count > 0){
                throw new ServiceException("该区域已存在变电站！");
            }
        }
        return toAjax(sAreaService.removeByIds(ids));
    }
}
